#include "useraptrepositorydialog.h"
#include "ui_useraptrepositorydialog.h"
#include "userquestiondialog.h"

#include <QDesktopServices>
#include <QDir>
#include <QStandardPaths>
#include <qrcutil.h>

UserAptRepositoryDialog::UserAptRepositoryDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UserAptRepositoryDialog)
{
    ui->setupUi(this);

    QFont font = ui->plainTextEdit->font();
    font.setFamily("Noto Mono");
    ui->plainTextEdit->setFont(font);

    QString distributions = getAppDistributions();

    if (distributions.trimmed().isEmpty() == false) {
        ui->plainTextEdit->setPlainText(distributions);
    } else {
        ui->plainTextEdit->setPlainText(QR("://rule.txt"));
    }
}

UserAptRepositoryDialog::~UserAptRepositoryDialog()
{
    delete ui;
}

QString UserAptRepositoryDialog::configDir()
{
    QString configDir = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
    return configDir + QDir::separator();
}

QString UserAptRepositoryDialog::appConfigDir()
{
    QString path = configDir() + "debian-apt-analyzer";
    return path + QDir::separator();
}

QString UserAptRepositoryDialog::appConfigFile()
{
    QString path = appConfigDir() + "/mirros.txt";
    return path;
}

QString UserAptRepositoryDialog::getAppDistributions()
{
    QDir dir;
    if (dir.exists() == false) {
        return "";
    }

    QFile file(appConfigFile());
    if (file.open(QFile::ReadOnly) == false) {
        return "";
    }
    return file.readAll();
}

void UserAptRepositoryDialog::setAppDistributions(const QString &mirrors)
{
    QDir dir;
    if (dir.exists(appConfigDir()) == false) {
        dir.mkdir(appConfigDir());
    }

    QFile file(appConfigFile());
    if (file.open(QFile::WriteOnly)) {
        file.write(mirrors.toUtf8());
        file.flush();
        file.close();
    }
}

void UserAptRepositoryDialog::on_buttonBox_accepted()
{
    setAppDistributions(ui->plainTextEdit->toPlainText());
}


void UserAptRepositoryDialog::on_commandLinkButton_clicked()
{
    QDesktopServices::openUrl(QUrl::fromUserInput("https://bbs.deepin.org.cn/post/275133?postId=1618845"));
}


void UserAptRepositoryDialog::on_pushButton_clicked()
{
    UserQuestionDialog dialog;
    dialog.setWindowTitle("用户问题");
    dialog.exec();
}

